package ve.edu.ucla.dals.servicio.server;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

public abstract class ServletHelper extends HttpServlet  {
	private static final long serialVersionUID = 1L;

	public abstract ServletResponseHelper doProcess(HttpServletRequest request) throws ServletHelperException;
	
	private void beforeDoProcess(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			ServletResponseHelper responseHelper = doProcess(request);
			responseHelper.apply(response);
		} catch (ServletHelperException e) {
			JSONObject json = new JSONObject();
			json.put("error", e.getErrorCode());
			json.put("causa", e.getMessage());
			new JsonServletResponseHelper(e.getHttpCode(), json).apply(response);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		beforeDoProcess(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		beforeDoProcess(request, response);
	}
}
